package com.erp.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.erp.common.R;
import com.erp.common.SuperConstant;
import com.erp.entity.User;
import com.erp.entity.UserGroup;
import com.erp.service.UserGroupService;
import com.erp.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/authorize")
@RequiresRoles(value = {"SupperAdministrator"})
public class AuthorizeController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserGroupService userGroupService;

    @PostMapping
    @RequiresPermissions("SupperAdministrator:add")
    public R<String> authorize(@RequestBody Map<String, String> map){
        Long id = Long.valueOf(map.get("id"));
        String name = map.get("name");

        User user = userService.getById(id);
        if (ObjectUtils.isEmpty(user)){
            return R.error("id不存在");
        }
        System.out.println(name);
        LambdaQueryWrapper<UserGroup> userGroupLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userGroupLambdaQueryWrapper.eq(UserGroup::getUserId,id);
        UserGroup userGroup = userGroupService.getOne(userGroupLambdaQueryWrapper);
        switch (name){
            case "SupperAdministrator":
                userGroup.setManagerId(SuperConstant.SupperAdministratorId);
                break;
            case "FinancialAdministrator":
                userGroup.setManagerId(SuperConstant.FinancialAdministratorId);
                break;
            case "LogisticsAdministrator":
                userGroup.setManagerId(SuperConstant.LogisticsAdministratorId);
                break;
            case "HrAdministrator":
                userGroup.setManagerId(SuperConstant.HrAdministratorId);
                break;
            default:
                userGroup.setManagerId(SuperConstant.DefaultManagerId);
        }
        userGroupService.updateById(userGroup);
        return R.success("成功");
    }
}
